<?php
namespace Admin\Model;
use Think\Model;
class StudentModel extends Model {
	protected $tableName = 'student'; // 表名称
	public $columns;	// 表结构
	
	/**
	 * 获取表结构
	 */
	public function column() {
		$name = C('DB_PREFIX').$this->tableName;
		$columns = M()->query('show full columns from '.$name);
		$this->columns = $columns;
		return $columns;
	}

	/**
	 * 验证字段
	 */
	public function checkform($method) {
		if(empty($this->columns)) { // 判断是否获取表结构
			$this->column();
		}

		$columns = $this->columns; // 表结构
		foreach($columns as $value) {
			if($value['key'] != 'PRI') { // 判断是否是主键
				$comment = json_decode($value['comment'],true);
				if($comment['time'] == 1) {
					$para = filter($method[$value['field']],$value['field']); // 过滤参数
					$msg = checkcolumn($para,$value['comment']); // 验证字段
					if(!empty($msg)) {
						return $msg;
					}
				} else if($comment['time'] == 2) {
				} else {
					if(isset($method[$value['field']])){ // 判断传参是否存在
						$para = filter($method[$value['field']],$value['field']); // 过滤参数
						$msg = checkcolumn($para,$value['comment']); // 验证字段
						if(!empty($msg)) {
							return $msg;
						}
					}
				}
			}
		}
	}

	/**
	 * 处理表单
	 */
	public function handleform($method) {
		if(empty($this->columns)) { // 判断是否获取表结构
			$this->column();
		}

		$columns = $this->columns; // 表结构
		foreach($columns as $value) {
			if($value['key'] == 'PRI') { // 判断是否是主键
				if(!empty($method[$value['field']])) {
					$where[$value['field']] = filter($method[$value['field']]);
				}
			} else {
				if(isset($method[$value['field']])) { // 判断传参是否存在
					$data[$value['field']] = filter($method[$value['field']],$value['field']); // 过滤参数
					$comment = json_decode($value['comment'],true);
					if(!empty($comment['filter'])) {
						$data[$value['field']] = $comment['filter']($data[$value['field']]);
					}
				}
			}
		}

		$telarr = $_POST['tel'];
		if(!empty($telarr)) {
			$contact = json_encode($telarr);
		} else{
			$contact = '';
		}
		$data['contact'] = $contact;
		if(empty($where)) {
			$data['num'] = time().rand(100,999);
			$data['time'] = time();
			$msg = $this->add($data);
		} else {
			$msg = $this->where($where)->save($data);
		}
		return $msg;
	}

}
